<template>
  <div class="pointPhoto">
    <div class="pointPhoto_left">
      <div class="pointPhoto_left_top">
        <el-button type="primary" class="pointPhoto_left_top_addTemplate" @click="addTemplate">新增模板</el-button>
        <el-select
          v-model="formDataTemp"
          placeholder="请选择模板"
          class="pointPhoto_left_top_selectTemplate"
          value-key="templateName"
          @change="changeTemplate"
          clearable
          @clear="addTemplate"
          style="margin:0 20px 0 30px;"
        >
          <el-option v-for="(obj, index) in template" :key="index" :value="obj" :label="obj.templateName"></el-option>
        </el-select>
      </div>
      <div class="pointPhoto_left_center">
        <el-form :model="formData" label-width="130px" :rules="rules" @submit.native.prevent ref="templateEditForm">
          <el-form-item label="模板名称：" prop="templateName">
            <el-input
              v-model.trim="formData.templateName"
              placeholder="请输入模板名称"
              :disabled="formData.isDisabled"
              @change="clearTable"
            ></el-input>
          </el-form-item>
          <div class="d-flex ai-center">
            <div class="flex-1">
              <el-form-item label="模板图片：" prop="templatePhoto">
                <el-upload
                  list-type="picture-card"
                  :action="QINIUUPLOADURL"
                  :data="qiniuData"
                  :limit="1"
                  v-model="formData.templatePhoto"
                  :before-upload="handleBeforeUpload"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
                >
                  <template v-slot:file="file">
                    <img id="templatePic" :src="file.file.url" alt width="100%" height="100%" crossorigin="anonymous" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(1)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </template>
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </div>
            <div class="flex-1">
              <el-form-item label="二维码头像：">
                <el-upload
                  list-type="picture-card"
                  :action="QINIUUPLOADURL"
                  :data="qiniuData"
                  :limit="1"
                  :before-upload="handleBeforeUpload"
                  :on-exceed="handleExceed"
                  :on-error="handleError"
                  :on-success="handleQrcodeAvatarSuccess"
                  :file-list="qrcodeAvatarFileList"
                  accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
                >
                  <template v-slot:file="file">
                    <img :src="file.file.url" alt width="100%" height="100%" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(2)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </template>
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </div>
          </div>
          <el-form-item label="模板宽高：" prop="templateWidth">
            <el-row type="flex" justify="space-between">
              <el-col :span="11">
                <el-form-item prop="templateWidth">
                  <el-input v-model.number="formData.templateWidth" placeholder="模板宽（单位像素）" @change="clearTable"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="templateHeight">
                  <el-input v-model.number="formData.templateHeight" placeholder="模板高（单位像素）" @change="clearTable"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="二维码位置：">
            <el-row type="flex" justify="space-between">
              <el-col :span="11">
                <el-form-item>
                  <el-input v-model.number="formData.qrcodePositionX" placeholder="二维码横坐标" @change="clearTable"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item>
                  <el-input v-model.number="formData.qrcodePositionY" placeholder="二维码纵坐标" @change="clearTable"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="二维码尺寸：">
            <el-input v-model.number="formData.qrcodeSize" placeholder="输入二维码的尺寸，默认200" @change="clearTable"></el-input>
          </el-form-item>
          <el-form-item prop="attributeTeam" label="选择文案：">
            <el-select v-model="formData.attributeTeam" placeholder="请选择文案" multiple value-key="attributeKey">
              <el-option v-for="(item, index) in attribute" :key="index" :value="item" :label="item.attributeName"></el-option>
            </el-select>
          </el-form-item>
          <div class="field-wrap" v-for="(item, index) in formData.attributeTeam" :key="index">
            <el-form-item>
              <h3>文案{{ index + 1 }}：{{ item.attributeName }}</h3>
            </el-form-item>
            <div class="d-flex ai-center">
              <div class="flex-1">
                <el-form-item label="横坐标：" :prop="`attributeTeam[${index}].positionX`" :rules="rules.positionX">
                  <el-input v-model.number="item.positionX" placeholder="横坐标（单位像素）" @change="clearTable"></el-input>
                </el-form-item>
              </div>
              <div class="flex-1">
                <el-form-item label="纵坐标：" :prop="`attributeTeam[${index}].positionY`" :rules="rules.positionY">
                  <el-input v-model.number="item.positionY" placeholder="纵坐标（单位像素）" @change="clearTable"></el-input>
                </el-form-item>
              </div>
            </div>
            <div class="d-flex ai-center">
              <div class="flex-1">
                <el-form-item label="字体大小：" :prop="`attributeTeam[${index}].fontSize`" :rules="rules.fontSize">
                  <el-input v-model.number="item.fontSize" placeholder="字体大小（单位像素）" @change="clearTable"></el-input>
                </el-form-item>
              </div>
              <div class="flex-1" style="height:62px;">
                <el-form-item label="字体颜色：">
                  <el-color-picker
                    v-model="item.fontColor"
                    :predefine="predefineColors"
                    @active-change="colorChange"
                    @click.native="clickColorPicker(index)"
                  ></el-color-picker>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="是否加粗：">
              <el-radio v-model="item.isBold" :label="true">是</el-radio>
              <el-radio v-model="item.isBold" :label="false">否</el-radio>
            </el-form-item>
            <el-form-item label="对齐方式：">
              <el-radio-group v-model="item.textAlign">
                <el-radio label="left">左对齐</el-radio>
                <el-radio label="center">居中对齐</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <el-form-item>
            <el-button type="primary" @click="saveTemplate">保存模板</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="pointPhoto_center">
      <h4 class="pointPhoto_center_top">已生成{{ productPhotoCount }}张图片</h4>
      <div class="pointPhoto_center_center">
        <div>
          <div class="action-tip text-left">1.从左侧新增或选择模板</div>
          <div class="action-tip text-left">2.选择点位</div>
          <div class="action-tip text-left">3.生成图片</div>
          <div class="action-tip text-left">4.下载图片</div>
        </div>
        <div
          v-if="formData.templatePhoto"
          class="pointPhoto_center_center_templateImage"
          :style="{
            'background-image': `url(${formData.templatePhoto})`,
            width: `${formData.templateWidth}px`,
            height: `${formData.templateHeight}px`,
            position: `absolute`,
            overflow: 'hidden',
            'z-index': '1',
          }"
        >
          <div
            v-for="(item, index) in formData.attributeTeam"
            :key="index"
            :style="{
              position: 'absolute',
              left: `${item.positionX}px`,
              top: `${item.positionY}px`,
              'font-size': `${item.fontSize}px`,
              'font-weight': item.isBold ? 'bold' : 'normal',
              'text-align': item.textAlign,
              color: `${item.fontColor}`,
              width: '100%',
            }"
          >
            <span>{{ item.attributeValue }}</span>
          </div>
          <vue-qr
            :text="formData.qrcode"
            :size="formData.qrcodeSize"
            :style="{
              position: 'absolute',
              left: `${formData.qrcodePositionX}px`,
              top: `${formData.qrcodePositionY}px`,
            }"
            :logoSrc="formData.qrCodeAvatar"
            :margin="0"
          ></vue-qr>
        </div>
        <template v-if="formData.templatePhoto">
          <div
            v-for="(obj, i) in tableData"
            :key="i"
            :id="'pointDom'+obj.id"
            ref="pointPhoto"
            class="pointPhoto_center_center_templateImage"
            :style="{
              'background-image': `url(${formData.templatePhoto})`,
              width: `${formData.templateWidth}px`,
              height: `${formData.templateHeight}px`,
              position: `absolute`,
              overflow: 'hidden',
              'z-index': `-${i}`,
            }"
          >
            <vue-qr
              :text="obj.pointCode"
              :size="formData.qrcodeSize"
              :style="{
                position: 'absolute',
                left: `${formData.qrcodePositionX}px`,
                top: `${formData.qrcodePositionY}px`,
              }"
              :logoSrc="formData.qrCodeAvatar"
              :margin="0"
              :logoScale="0.2"
            ></vue-qr>
          </div>
        </template>
        <canvas
          v-for="(obj, i) in tableData"
          :key="'canvas'+i"
          :id="'pointCanvas'+obj.id"
          :width="formData.templateWidth"
          :height="formData.templateHeight"
          style="position:absolute;z-index:-1;"
        ></canvas>
      </div>
    </div>
    <div class="pointPhoto_right">
      <div class="pointPhoto_right_top">
        <el-button
          type="primary"
          plain
          class="pointPhoto_right_top_button"
          icon="el-icon-search"
          @click="selectPoint"
        >选择点位</el-button>
        <el-button type="primary" class="pointPhoto_right_top_button" icon="el-icon-picture" @click="productPhoto">生成图片</el-button>
        <el-button
          type="success"
          class="pointPhoto_right_top_button"
          icon="el-icon-download"
          @click="downloadPhoto"
        >下载图片</el-button>
      </div>
      <div class="pointPhoto_right_center">
        <el-table
          border
          :height="'calc(100vh - 250px)'"
          :data="
            tableData.slice(
              (this.currentPage - 1) * this.pageSize,
              (this.currentPage - 1) * this.pageSize + this.pageSize
            )
          "
          highlight-current-row
          @row-click="rowClick"
        >
          <el-table-column align="center" type="index" label="序号" width="50">
            <template v-slot="sc">{{sc.$index+1+pageSize*(currentPage-1)}}</template>
          </el-table-column>
          <el-table-column align="left" label="名称" prop="name"></el-table-column>
          <el-table-column align="center" label="编号" prop="pointCode" show-overflow-tooltip></el-table-column>
        </el-table>
        <el-pagination
          v-if="tableData.length"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[10, 50, 100]"
          layout="total, sizes, prev, next"
          :pager-count="5"
          :total="tableData.length"
        ></el-pagination>
      </div>
    </div>
    <point-message v-if="visiblePointMessage" @closePointMessage="closePointMessage"></point-message>
  </div>
</template>

<script>
import { qnToken } from '@/api/api'
import PointMessage from './Dialog/PointMessage'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

export default {
  components: {
    PointMessage,
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      visiblePointMessage: false,
      template: [],
      tableData: [],
      formDataTemp: {},
      colorPickerIndex: '',
      fileList: [],
      qrcodeAvatarFileList: [],
      srcArr: [],
      productPhotoCount: 0,
      formData: {
        isDisabled: false,
        templateName: '',
        templatePhoto: '',
        fileObj: {},
        qrcode: '测试二维码',
        qrCodeAvatar: '',
        qrcodeSize: 200,
        qrcodePositionX: 0,
        qrcodePositionY: 0,
        templateWidth: 600,
        templateHeight: 900,
        attributeTeam: [], // 多选的内容
      },
      attribute: [
        // 多选项
        {
          attributeKey: 1,
          attributeValue: '名称区域示例',
          attributeName: '名称',
          positionX: 0,
          positionY: 0,
          fontSize: 30,
          fontColor: '#000000',
          isBold: false,
          textAlign: 'left',
        },
        {
          attributeKey: 2,
          attributeValue: '编码区域示例',
          attributeName: '编码',
          positionX: 0,
          positionY: 0,
          fontSize: 30,
          fontColor: '#000000',
          isBold: false,
          textAlign: 'left',
        },
      ],
      predefineColors: [
        '#000000',
        '#ffffff',
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
      ],
      qiniuData: {
        token: '',
      },
      rules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
        ],
        templatePhoto: [
          { required: true, message: '请上传模板图片', trigger: 'blur' },
        ],
        templateWidth: [
          { required: true, message: '请输入模板宽', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
        templateHeight: [
          { required: true, message: '请输入模板高', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
        attributeTeam: [
          { required: true, message: '请选择文案', trigger: 'blur' },
        ],
        positionX: [
          { required: true, message: '请输入横坐标', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
        positionY: [
          { required: true, message: '请输入纵坐标', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
        fontSize: [
          { required: true, message: '请输入字体大小', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
        qrcodeSize: [
          { required: true, message: '请输入字体大小', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.initAttribute()
    this.getToken()
  },
  activated() {
    this.getStorageTemplate()
  },
  methods: {
    drawCanvas(item) {
      var c = document.getElementById('pointCanvas' + item.id)
      var ctx = c.getContext('2d')
      var img = document.getElementById('templatePic')
      ctx.drawImage(
        img,
        0,
        0,
        this.formData.templateWidth,
        this.formData.templateHeight
      )
      this.formData.attributeTeam.forEach((n) => {
        ctx.font = 'normal ' + n.fontSize + 'px Microsoft YaHei'
        ctx.textAlign =
          n.textAlign == 'left'
            ? 'start'
            : n.textAlign == 'center'
            ? 'center'
            : 'end'
        ctx.textBaseline = 'top'
        let x = 0
        if (n.textAlign == 'left') {
          x = n.positionX
        } else if (n.textAlign == 'center') {
          x = (this.formData.templateWidth - n.positionX) / 2
        }
        ctx.fillStyle = n.fontColor
        ctx.fillText(
          n.attributeKey == 1 ? item.name : item.pointCode,
          x,
          n.positionY
        )
      })
      let imgQr = document.querySelector('#pointDom' + item.id + ' img')
      ctx.drawImage(
        imgQr,
        this.formData.qrcodePositionX,
        this.formData.qrcodePositionY,
        this.formData.qrcodeSize,
        this.formData.qrcodeSize
      )
      return c
    },
    // 读取本地保存模板
    getStorageTemplate() {
      let localTmpl = localStorage.getItem('templateInfo') || '[]'
      fetch('/ilink-fe-config/zhxf-pc/pointQrcode.json')
        .then((res) => res.text())
        .then((data) => {
          if (data) {
            let arr = JSON.parse(data)
            this.template = arr.concat(JSON.parse(localTmpl))
          } else {
            this.template = JSON.parse(localTmpl)
          }
        })
        .catch(() => {})
    },
    // 保存模板
    saveTemplate() {
      this.$refs['templateEditForm'].validate((valid) => {
        if (valid) {
          this.formData.isDisabled = true
          this.formData.attributeTeam.forEach((item) => {
            if (item.attributeKey === 1) {
              item.attributeValue = '名称区域示例'
            } else if (item.attributeKey === 2) {
              item.attributeValue = '编码区域示例'
            }
          })
          if (JSON.parse(localStorage.getItem('templateInfo'))) {
            let tempArr = JSON.parse(localStorage.getItem('templateInfo'))
            let flagIndex = tempArr.findIndex((item) => {
              return item.templateName === this.formData.templateName
            })
            if (flagIndex >= 0) {
              tempArr[flagIndex] = this.formData
            } else {
              tempArr.push(this.formData)
            }
            localStorage.setItem('templateInfo', JSON.stringify(tempArr))
          } else {
            localStorage.setItem(
              'templateInfo',
              JSON.stringify([this.formData])
            )
          }
          this.template = JSON.parse(localStorage.getItem('templateInfo'))
          this.$message.success('保存成功！')
        }
      })
    },
    // 初始化默认文案
    initAttribute() {
      this.formData.attributeTeam.push(
        ...[
          {
            attributeKey: 1,
            attributeValue: '名称区域示例',
            attributeName: '名称',
            positionX: 0,
            positionY: 0,
            fontSize: 30,
            fontColor: '#000000',
            isBold: false,
            textAlign: 'left',
          },
          {
            attributeKey: 2,
            attributeValue: '编码区域示例',
            attributeName: '编码',
            positionX: 0,
            positionY: 0,
            fontSize: 30,
            fontColor: '#000000',
            isBold: false,
            textAlign: 'left',
          },
        ]
      )
    },
    // 选择点位
    selectPoint() {
      this.visiblePointMessage = true
    },
    // 关闭对话框
    closePointMessage(pointSelection) {
      if (pointSelection) {
        this.tableData = pointSelection
        this.srcArr = []
      }
      this.visiblePointMessage = false
    },
    // 切换页条目数
    handleSizeChange(pageSize) {
      this.currentPage = 1
      this.pageSize = pageSize
    },
    // 翻页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    // 单选
    rowClick(row) {
      this.formData.qrcode = row.pointCode
      this.formData.attributeTeam.forEach((item) => {
        if (item.attributeKey === 1) {
          item.attributeValue = row.name
        } else if (item.attributeKey === 2) {
          item.attributeValue = row.pointCode
        }
      })
    },
    // 上传之前获取 token
    getToken() {
      let that = this
      qnToken({}).then((result) => {
        that.qiniuData.token = result.data
      })
    },
    // 超出上传数目
    handleExceed() {
      this.$message.error('只能上传一个模板！')
    },
    // 上传前验证
    handleBeforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      if (
        !'png,jpg,jpeg,bmp,gif'.includes(
          file.type.split('/')[file.type.split('/').length - 1].toLowerCase()
        )
      ) {
        this.$message.error('文件格式不正确')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    // 上传模板成功
    handleSuccess(response, file, fileList) {
      file.url =
        QINIUUPLOADURL.indexOf('uploadFile') > -1
          ? file.response.data
          : QINIUPATH + file.response.key
      this.fileList.push(file)
      this.formData.fileObj = file
      this.formData.templatePhoto =
        QINIUUPLOADURL.indexOf('uploadFile') > -1
          ? file.response.data
          : QINIUPATH + file.response.key
    },
    // 上传二维码头像成功
    handleQrcodeAvatarSuccess(response, file, fileList) {
      file.url =
        QINIUUPLOADURL.indexOf('uploadFile') > -1
          ? file.response.data
          : QINIUPATH + file.response.key
      this.qrcodeAvatarFileList.push(file)
      this.formData.qrcodeAvatarfileObj = file
      this.formData.qrCodeAvatar =
        QINIUUPLOADURL.indexOf('uploadFile') > -1
          ? file.response.data
          : QINIUPATH + file.response.key
    },
    // 上传失败
    handleError() {
      this.$message.error('上传失败！')
    },
    // 删除操作
    handleRemove(flag) {
      if (flag == 1) {
        this.formData.templatePhoto = ''
        this.fileList = []
      } else if (flag == 2) {
        this.formData.qrCodeAvatar = ''
        this.qrcodeAvatarFileList = []
      }
    },
    // 颜色改变
    colorChange(color) {
      this.formData.attributeTeam[this.colorPickerIndex].fontColor = color
    },
    // 点击el-color-picker
    clickColorPicker(index) {
      this.colorPickerIndex = index
    },
    // 新增模板
    addTemplate() {
      this.fileList = []
      ;(this.qrcodeAvatarFileList = []), (this.formDataTemp = {})
      this.formData = {
        isDisabled: false,
        templateName: '',
        templatePhoto: '',
        qrCodeAvatar: '',
        qrcode: '测试二维码',
        qrcodeSize: 200,
        qrcodePositionX: 0,
        qrcodePositionY: 0,
        templateWidth: 600,
        templateHeight: 900,
        fileObj: {}, // 记录上传模板图片信息
        qrcodeAvatarfileObj: {}, // 记录上传二维码头像信息
        attributeTeam: [
          {
            attributeKey: 1,
            attributeValue: '名称区域示例',
            attributeName: '名称',
            positionX: 0,
            positionY: 0,
            fontSize: 30,
            fontColor: '#000000',
            isBold: false,
            textAlign: 'left',
          },
          {
            attributeKey: 2,
            attributeValue: '编码区域示例',
            attributeName: '编码',
            positionX: 0,
            positionY: 0,
            fontSize: 30,
            fontColor: '#000000',
            isBold: false,
            textAlign: 'left',
          },
        ], // 多选的内容
      }
    },
    // 切换模板
    changeTemplate(val) {
      this.tableData = []
      this.srcArr = []
      this.formData = JSON.parse(JSON.stringify(val))
      this.fileList = []
      this.qrcodeAvatarFileList = []
      this.fileList.push(this.formData.fileObj)
      this.qrcodeAvatarFileList.push(this.formData.qrcodeAvatarfileObj)
    },
    clearTable() {
      this.tableData = []
      this.srcArr = []
    },
    // 生成图片
    productPhoto() {
      if (this.tableData.length <= 0) {
        return this.$message.error('请选择点位数据！')
      } else if (!this.formData.templatePhoto) {
        return this.$message.error('请创建模板！')
      } else if (this.srcArr.length > 0) {
        return this.$message.success('生成图片完成！')
      }
      let srcArr = []
      let opts = {
        width: this.formData.templateWidth,
        height: this.formData.templateHeight,
        useCORS: true,
      }
      this.tableData.forEach((item) => {
        srcArr.push({ name: item.name })
      })
      this.tableData.forEach((n, i) => {
        let canvas = this.drawCanvas(n)
        this.$nextTick(() => {
          srcArr[i]['url'] = canvas.toDataURL()
        })
      })
      this.srcArr = srcArr
      this.productPhotoCount = srcArr.length
      this.$message.success('生成图片完成！')
    },
    // 下载图片
    downloadPhoto() {
      if (this.srcArr.length <= 0) {
        return this.$message.error('请点击生成图片后再下载图片！')
      }
      let zip = new JSZip()
      let qrCodeImg = zip.folder('AllQrCode')
      let srcArr = this.srcArr
      let srcArrL = this.srcArr.length
      for (var i = 0; i < srcArrL; i++) {
        var blobData = this.dataURLtoBlob(srcArr[i].url)
        qrCodeImg.file(`${i + 1 + '-' + srcArr[i].name}.png`, blobData, {
          base64: true,
        })
        if (i == srcArrL - 1) {
          //循环结束保存压缩包
          //将zip序列化为二进制流
          zip.generateAsync({ type: 'blob' }).then(function (content) {
            let fileName = '巡检点位'
            saveAs(content, `${fileName}(${srcArrL}).zip`)
          })
        }
      }
    },
    // urL图片转base64
    // getBase64Image(imgSrc) {
    //   let img = new Image()
    //   // img.crossOrigin = ''
    //   img.src = imgSrc

    //   let canvas = document.createElement('canvas')
    //   canvas.width = img.width
    //   canvas.height = img.height

    //   let ctx = canvas.getContext('2d')
    //   ctx.drawImage(img, 0, 0, img.width, img.height)
    //   let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
    //   let dataURL = canvas.toDataURL('image/' + ext)
    //   return dataURL
    // },
    // dataURL转blob
    dataURLtoBlob(dataurl) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
  },
  computed: {},
}
</script>

<style lang="scss">
.pointPhoto {
  display: flex;
  justify-content: space-between;
  .field-wrap {
    border: 1px dashed #ccc;
    padding-right: 20px;
    margin-bottom: 20px;
  }
  .el-upload--picture-card,
  .el-upload-list__item {
    width: 100px;
    height: 100px;
    line-height: 98px;
  }
  .pointPhoto_left_center {
    padding-right: 10px;
    height: calc(100vh - 200px);
    overflow-y: auto;
  }
  .pointPhoto_left {
    width: 500px;
    .pointPhoto_left_top {
      display: flex;
      margin-bottom: 20px;
      .pointPhoto_left_top_addTemplate {
        width: 20%;
      }
      .pointPhoto_left_top_selectTemplate {
        width: 70%;
      }
    }
  }
  .pointPhoto_center {
    margin: 0 20px;
    flex-grow: 1;
    display: flex;
    padding: 0 20px;
    flex-direction: column;
    align-items: center;
    border: 1px dashed #ccc;
    .action-tip {
      color: #ccc;
      font-size: 20px;
      line-height: 26px;
    }
    .pointPhoto_center_top {
      margin-bottom: 20px;
      width: 100%;
      text-align: right;
      line-height: 40px;
    }
    .pointPhoto_center_center {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      flex: 1;
      width: 100%;
      position: relative;
      line-height: 1;
      .pointPhoto_center_center_templateImage {
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
      }
    }
  }
  .pointPhoto_right {
    width: 400px;
    .pointPhoto_right_top {
      display: flex;
      justify-content: space-between;
    }
    .pointPhoto_right_center {
      padding-top: 20px;
    }
  }
}
</style>